package 二分查找;

import java.util.Arrays;

public class BinarySearch {
    public static void main(String[] args) {
        int[] arr = {1, 1, 2, 3, 3, 5, 11, 13, 15, 15, 16};
//        System.out.println(binaryseach(arr, 3));
//        System.out.println(binaryseach2(arr, 15));
//        System.out.println(binaryseach3(arr, 15));
        System.out.println(binaryseach4(arr, 15));
        System.out.println(binaryseach5(arr, 15));

    }


    public static int binaryseach(int[] arr, int target) {
        int left = 0;
        int right = arr.length;
        while (left < right) {
            int mid = (left + right) >>> 1;
            if (arr[mid] <= target) {
                left = mid;
            } else {
                right = mid - 1;
            }
            if (arr[mid] == target) return mid;
        }
        return -1;
    }


    public static int binaryseach2(int[] arr, int target) { // 二分查找 查找第一次出现
        int l = 0;
        int r = arr.length;
        while (l < r) {
            int mid = (l + r) >>> 1;
            if (arr[mid] >= target) {
                r = mid;
            } else {
                l = mid + 1;
            }
        }
        if (arr[l] == target) return l;
        else return -1;
    }

    public static int binaryseach3(int[] arr, int target) { // 二分查找 查找第一次出现
        int l = 0;
        int r = arr.length;
        while (l < r) {
            int mid = (l + r + 1) >>> 1;
            if (arr[mid] <= target) {
                l = mid;
            } else {
                r = mid - 1;
            }
        }
        if (arr[l] == target) return l;
        return -1;
    }

    //第一次出现  最小
    public static int binaryseach4(int[] arr, int target) {
        int l = 0;
        int r = arr.length;
        while (l < r) {
            int mid = (l + r) >>> 1;
            if (arr[mid] >= target) {
                r = mid;
            } else {
                l = mid + 1;
            }
        }
        if (arr[l] == target) return l;
        else return -1;
    }
    //最后一次出现 最大
    public static int binaryseach5(int[] arr, int target) {
        int l = 0;
        int r = arr.length;
        while (l < r) {
            int mid = (l + r + 1) >>> 1;
            if (arr[mid] <= target) {
                l = mid;
            } else {
                r = mid - 1;
            }
        }
        if (arr[l] == target) return l;
        else return -1;
    }
}
